package com.kws.tool.service.impl;

import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.config.util.DateTimeUtil;
import com.kws.common.core.exception.ServiceException;
import com.kws.tool.config.MinioAPI;
import com.kws.tool.service.UploadFileService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;

/**
 * <b>UploadFileServiceImpl</b>
 *
 * @description: UploadFileServiceImpl <br>
 * @date: 2024/11/22 14:18 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class UploadFileServiceImpl implements UploadFileService {
    private static final Logger logger = LoggerFactory.getLogger(UploadFileServiceImpl.class);

    @Autowired
    private MinioAPI minioAPI;

    private final static String SLASH = "/";

    private final static String FILE_NAME_PREFIX_SEPARATOR = "-";

    @Value("${minio.ENDPOINT}")
    private String minioUrl;

    @Override
    public String uploadFile(MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            String bucketName = MinioCommonBucket.HUATAI_PUB_BUCKET;
            String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
            minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
            logger.info("上传地址为:{}"+objectKey);
            return minioUrl+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET+"/"+objectKey;
        } catch (Exception e) {
            logger.error("上传失败，", e);
            throw new ServiceException("上传失败，请重新上传");
        }
    }

    private String getObjectKey(Long fileSize,String fileName) {
        String date = DateTimeUtil.format(LocalDate.now(),"yyyyMMdd");

        StringBuilder objectKey = new StringBuilder(date);
        objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
        return objectKey.toString();
    }
}
